#! /bin/sh

UMS_EN=off
MTP_EN=off
ADB_EN=off
UMS_AUTO_MOUNT=off
UMS_BLOCK=/dev/block/by-name/userdata
PATH_TO_UMS_FILE=/sys/kernel/config/usb_gadget/rockchip/functions/mass_storage.0/lun.0/file
PATH_TO_USB_CONFIG=/tmp/.usb_config
PATH_TO_UDC=/sys/kernel/config/usb_gadget/rockchip/UDC

find_ums_config()
{
	while read line
	do
		NAME=`echo $line | awk -F "=" '{print $1}'`
		VAR=`echo $line | awk -F "=" '{print $2}'`

		if [ "$NAME" == "ums_block" ]; then
			UMS_BLOCK=${VAR}
		fi

		if [ "$NAME" == "ums_block_auto_mount" ]; then
			UMS_AUTO_MOUNT=${VAR}
		fi
	done < ${PATH_TO_USB_CONFIG}
}

find_spec_function()
{
	functions=`cat /sys/kernel/config/usb_gadget/rockchip/configs/b.1/strings/0x409/configuration`

	functions=${functions}_over_
	tmp=`echo $functions | awk -F "_" '{print $1}'`

	while [ "${tmp}" != "over" ]; do
		test "$tmp" == "mtp" && MTP_EN=on
		test "$tmp" == "ums" && UMS_EN=on
		test "$tmp" == "adb" && ADB_EN=on
		functions=${functions#*_}
		tmp=`echo $functions | awk -F "_" '{print $1}'`
	done
}

dev_path=/sys$1
state=$2

find_spec_function
if [ "$state"x != "CONFIGURED"x  ] ; then

	if [ $MTP_EN = on ]; then
		pgrep mtp-server
		echo "mtp-server runing:" $?
		if ! pgrep -f mtp-server; then
			start-stop-daemon --start --quiet --background --exec /usr/bin/mtp-server
		fi
	fi

	if [ $ADB_EN = on ] && [ "$state"x = "DISCONNECTED"x ] ; then
		cat ${PATH_TO_USB_CONFIG} | grep USB_FORCE_CHANGED || \
			/etc/init.d/S50usbdevice restart
	fi
else
	if [ $UMS_EN = on ]; then
		find_ums_config
		if [ $UMS_AUTO_MOUNT = on ]; then
			umount -f /mnt/ums
		fi
		VAR=`cat ${PATH_TO_UMS_FILE}`
		test -z ${VAR} && echo ${UMS_BLOCK} > ${PATH_TO_UMS_FILE}
	fi
fi
